package inf.coach.mobile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.List;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Environment;
import android.view.View.OnKeyListener;
import android.view.View;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.KeyEvent;

import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;


public class GpsTest extends MapActivity {
    LocationManager locationManager;
    MapView map_view;
    TextView Lat;
    TextView Lng;
    TextView time;
    Location location;
    String provider;
    EditText text_location;

     @Override   
      public void onCreate(Bundle savedInstanceState) {  
          super.onCreate(savedInstanceState);  
         setContentView(R.layout.gpstest);
         
         Lat=(TextView)findViewById(R.id.textView_lat);
         Lng=(TextView)findViewById(R.id.textView_ing);
         time=(TextView)findViewById(R.id.textView_time);
         text_location=(EditText)findViewById(R.id.editText_location);
         
    
       //add bank button onclick event

        //set MapControl 
        Button back=(Button)findViewById(R.id.back);
        final Button ok=(Button)findViewById(R.id.button_start);
        
        
        back.setOnClickListener(new Button.OnClickListener(){
        	
        	public void onClick(View arg0){
        		
        		locationManager.removeUpdates(locationListener);
        		writeFileToSD("===================================================");
        		   finish();
    
        	}
        	
        });
        
        ok.setOnClickListener(new Button.OnClickListener(){
        	
        	public void onClick(View arg0){
        		writeFileToSD("============("+text_location.getText()+")=============");
        		
                location =locationManager.getLastKnownLocation(provider);
        		
        		 if(location!=null)
        	        {
        	            UpdateMapView(location);
        	        }
        	            
        	        locationManager.requestLocationUpdates(provider, 5000, 0, locationListener );
        	     text_location.setEnabled(false); 
        	     ok.setClickable(false);
        	}
        	
        });
        /*map_view =(MapView)findViewById(R.id.mapview);
        map_view.setTraffic(true);
        map_view.setBuiltInZoomControls(false);
        map_view.setSatellite(false);  
        
        List<Overlay> overlays=map_view.getOverlays(); // set location Overlay
        MyLocationOverlay mylocationOver=new MyLocationOverlay(this,map_view);
        overlays.add(mylocationOver);
        mylocationOver.enableCompass();
        mylocationOver.enableMyLocation();*/
        
        //set atm Overlay

        String context=Context.LOCATION_SERVICE;
        locationManager=(LocationManager)getSystemService(context);
        provider=LocationManager.GPS_PROVIDER;
        //OverlayItem a=new OverlayItem(null, provider, provider;

       
    
     }
     
     /* By new location ,update MapWiew's Label */
     private void UpdateMapView(Location location)
     {
           //MapController mapcontroller=map_view.getController();

            Double lat=location.getLatitude();
            Double lng=location.getLongitude();
            Lat.setText(lat.toString());
            Lng.setText(lng.toString());
            long sysTime = System.currentTimeMillis();
            CharSequence sysTimeStr = DateFormat.format("hh:mm:ss", sysTime);
            time.setText(sysTimeStr);

            writeFileToSD(lat+","+lng+"/"+sysTimeStr);
            Log.d("TestFile","write file");
           /* lat=lat*1E6;
            lng=lng*1E6;
            GeoPoint point=new GeoPoint(lat.intValue(),lng.intValue());
          
            mapcontroller.setCenter(point);
            mapcontroller.setZoom(20);
            mapcontroller.animateTo(point);*/
          
     }
     
     @Override
        public boolean onKeyDown(int keyCode, KeyEvent event) {
            if(keyCode == KeyEvent.KEYCODE_BACK){
            }
                return false;
        }
    @Override
    protected boolean isRouteDisplayed() {
        // TODO Auto-generated method stub
        return false;
    }

     //create location listener
        private LocationListener locationListener = new LocationListener(){
              //location is changed
            @Override
             public void onLocationChanged(Location location) {
                UpdateMapView(location);
                 Log.d("Location", "onLocationChanged");
             }
    
             //location is Disable
       @Override
             public void onProviderDisabled(String provider) {
               Log.d("Location", "onProviderDisabled");
             }
    
            //location is enabled
             @Override
           public void onProviderEnabled(String provider) {
            Log.d("Location", "onProviderEnabled");
             }
     
             //location's status changes
             @Override
             public void onStatusChanged(String provider, int status, Bundle extras) {
                Log.d("Location", "onStatusChanged");
             }
     };
     
     private void writeFileToSD(String s) {

    	 String sdStatus = Environment.getExternalStorageState();

    	 if(!sdStatus.equals(Environment.MEDIA_MOUNTED)) {

    		 Log.d("TestFile", "SD card is not avaiable/writeable right now.");

    		 return;
    	 }

    	try {

    	String pathName="/sdcard/test/";

    	String fileName="gps.txt";

    	File path = new File(pathName);

    	File file = new File(pathName + fileName);

    	if( !path.exists()) {

    	Log.d("TestFile", "Create the path:" + pathName);

    	path.mkdir();

    	}

    	if( !file.exists()) {

    	Log.d("TestFile", "Create the file:" + fileName);

    	file.createNewFile();

    	}
    	
    	Writer fw = new FileWriter("/sdcard/test/gps.txt", true);
    	fw.write("\r\n"+s);
    	fw.close();

/*    	FileOutputStream stream = new FileOutputStream(file);
    	OutputStreamWriter writer = new OutputStreamWriter(stream, "UTF-8");

    	writer.append(s);
    	writer.append("\r\n");
    	writer.flush();
    	writer.close();
    	stream.close();*/

    	}
    	catch(Exception e) {

    	Log.e("TestFile", "Error on writeFilToSD.");

    	e.printStackTrace();
    	}
    	}
 
}